package com.imooc.imoocbilibili.utils;

import cn.hutool.core.util.StrUtil;

public class CompareVersionUtil {

	/**
	 * 三种情况：
	 * 	1、当前版本 > 传入的版本 返回 -1
	 * 	2、当前版本 = 传入的版本 返回 0
	 * 	3、当前版本 < 传入的版本 返回 1
	 * @param onlineVersion 数据库中查询出来的版本
	 * @param currentVersion 当前版本
	 */
	public static int compareVersion(String onlineVersion, String currentVersion) {
		if (onlineVersion.equals(currentVersion)) {
			return 0;
		}
		if (StrUtil.isBlank(onlineVersion) && StrUtil.isNotBlank(currentVersion)) {
			return -1;
		}
		if (StrUtil.isNotBlank(onlineVersion) && StrUtil.isBlank(currentVersion)) {
			return 1;
		}

		String[] version1Array = onlineVersion.split("\\.");
		String[] version2Array = currentVersion.split("\\.");
		int index = 0;
		//获取最小长度值
		int minLen = Math.min(version1Array.length, version2Array.length);
		int diff = 0;
		//循环判断每位的大小
		while (index < minLen && (diff = Integer.parseInt(version1Array[index]) - Integer.parseInt(version2Array[index])) == 0) {
			index++;
		}
		if (diff == 0) {
			//如果位数不一致，比较多余位数
			for (int i = index; i < version1Array.length; i++) {
				if (Integer.parseInt(version1Array[i]) > 0) {
					return 1;
				}
			}

			for (int i = index; i < version2Array.length; i++) {
				if (Integer.parseInt(version2Array[i]) > 0) {
					return -1;
				}
			}
			return 0;
		} else {
			return diff > 0 ? 1 : -1;
		}
	}

	public static void main(String[] args) {
		String v1 = "";
		String v2 = "1.0.0.1";
		String v3 = "1.0.0.2";
		String v4 = "1.0.1";
		String v5 = "1.2.1";
		System.out.println(compareVersion(v1,v2));
		System.out.println(compareVersion(v2,v3));
		System.out.println(compareVersion(v3,v4));
		System.out.println(compareVersion(v4,v5));
		System.out.println(compareVersion(v4,v1));
	}
}
